// SMSLib for Java v3
// A Java API library for sending and receiving SMS via a GSM modem
// or other supported gateways.
// Web Site: http://www.smslib.org
//
// Copyright (C) 2002-2011, Thanasis Delenikas, Athens/GREECE.
// SMSLib is distributed under the terms of the Apache License version 2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.terdidik.smsserver.interfaces;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Properties;

import org.smslib.InboundMessage;
import org.smslib.Message.MessageEncodings;
import org.smslib.Message.MessageTypes;
import org.smslib.OutboundMessage;
import org.smslib.helper.ExtStringBuilder;
import org.smslib.helper.Logger;
import org.smslib.smsserver.SMSServer;
import org.smslib.smsserver.interfaces.Interface;

import com.terdidik.smsserver.helper.Transformer;

/**
 * Interface for http communication with SMSServer. <br />
 * 
 * @author Ernas M. Jamil
 * @author Sebastian Just - Added POST suppport (Issue 133)
 */
public class HttpXml extends Interface<Integer>
{
	
	private static final SimpleDateFormat localSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	public HttpXml(String myInterfaceId, Properties myProps, SMSServer myServer, InterfaceTypes myType)
	{
		super(myInterfaceId, myProps, myServer, myType);
		setDescription("HTTPXML interface.");
	}

	@Override
	public void messagesReceived(Collection<InboundMessage> msgList) throws Exception
	{
		String template = getProperty("rec_url");
		Logger.getInstance().logInfo("SMSServer: Interface HTTPXML: " + template, null, null);
		for (InboundMessage im : msgList)
		{
			if (template != null && ((im.getType() == MessageTypes.INBOUND) || (im.getType() == MessageTypes.STATUSREPORT)))
			{
				String retURL = updateInboundTemplateString(template, im);
				Logger.getInstance().logDebug("SMSServer: Interface HTTPXML: " + retURL, null, null);
				URL url = new URL(retURL);
				String r=HttpDo(url);
				Logger.getInstance().logDebug("SMSServer: Interface HTTPXML: "+retURL+">>>" + r, null, null);
			}
		}
	}

	@Override
	public void markMessage(OutboundMessage om) throws Exception
	{
		String template = getProperty("mark_url");
		Logger.getInstance().logInfo("SMSServer: Interface HTTPXML: " + template, null, null);
		if (template != null)
		{
			String dlrURL = updateOutboundTemplateString(template, om);
			Logger.getInstance().logDebug("SMSServer: Interface HTTPXML: " + dlrURL, null, null);
			URL url = new URL(dlrURL);
			String r=HttpDo(url);
			Logger.getInstance().logDebug("SMSServer: Interface HTTPXML: " + dlrURL + ">>>" + r, null, null);
		}
		getMessageCache().remove(om.getId());
	}

	@Override
	public Collection<OutboundMessage> getMessagesToSend() throws Exception
	{
		Collection<OutboundMessage> om=new ArrayList<OutboundMessage>();
		String template=getProperty("get_url");
		Logger.getInstance().logInfo("SMSServer: Interface HTTP: " + template, null, null);
		if(template != null)
		{
			String retURL = template;
			URL url = new URL(retURL);
			String xml=HttpDo(url);
			Logger.getInstance().logDebug("SMSServer: Interface HTTPXML: " + retURL + ">>>" + xml, null, null);
			Transformer t=new Transformer();
			om=t.xmlToOutboundMessages(xml);
		}
		return om;
	}

	String HttpDo(URL url) throws IOException
	{
		if ("POST".equalsIgnoreCase(getProperty("method"))) return HttpPost(url);
		return HttpGet(url);
	}

	String HttpPost(URL url) throws IOException
	{
		StringBuilder sb=new StringBuilder();
		URL cleanUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getPath());
		Logger.getInstance().logInfo("HTTP POST: " + cleanUrl, null, null);
		URLConnection con = cleanUrl.openConnection();
		con.setAllowUserInteraction(false);
		con.setDoOutput(true);
		OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
		out.write(url.getQuery());
		out.flush();
		
		BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
		String inputLine;
		while ((inputLine = in.readLine()) != null)
			sb.append(inputLine);
		out.close();
		in.close();
		return sb.toString();
	}

	String HttpGet(URL url) throws IOException
	{
		StringBuilder sb=new StringBuilder();
		Logger.getInstance().logInfo("HTTP GET: " + url, null, null);
		URLConnection con = url.openConnection();
		con.setAllowUserInteraction(false);
		BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
		String inputLine;
		while ((inputLine = in.readLine()) != null)
			sb.append(inputLine);
		in.close();
		return sb.toString();
	}

	private String updateInboundTemplateString(String template, InboundMessage msg) throws UnsupportedEncodingException
	{
		ExtStringBuilder sb = new ExtStringBuilder(template);
		sb.replaceAll("%gatewayId%", URLEncoder.encode(msg.getGatewayId(), getProperty("encoding", "ISO-8859-1")));
		sb.replaceAll("%encoding%", (msg.getEncoding() == MessageEncodings.ENC7BIT ? "7" : (msg.getEncoding() == MessageEncodings.ENC8BIT ? "8" : "U")));
		if(msg.getDate() != null) sb.replaceAll("%date%", URLEncoder.encode(msg.getDate().toString(), getProperty("encoding", "ISO-8859-1")));
		if(msg.getDate() != null) sb.replaceAll("%ldate%", URLEncoder.encode(localSdf.format(msg.getDate()),getProperty("encoding", "ISO-8859-1")));
		sb.replaceAll("%text%", URLEncoder.encode(msg.getText(), getProperty("encoding", "ISO-8859-1")));
		sb.replaceAll("%originator%", msg.getOriginator());
		sb.replaceAll("%memIndex%", msg.getMemIndex());
		sb.replaceAll("%mpMemIndex%", msg.getMpMemIndex());
		return sb.toString();
	}

	private String updateOutboundTemplateString(String template, OutboundMessage msg) throws UnsupportedEncodingException
	{
		ExtStringBuilder sb = new ExtStringBuilder(template);
		sb.replaceAll("%messageId%", URLEncoder.encode(msg.getId(),"ISO-8859-1"));
		sb.replaceAll("%gatewayId%", URLEncoder.encode(msg.getGatewayId(), getProperty("encoding", "ISO-8859-1")));
		sb.replaceAll("%encoding%", (msg.getEncoding() == MessageEncodings.ENC7BIT ? "7-bit" : (msg.getEncoding() == MessageEncodings.ENC8BIT ? "8-bit" : "UCS2 (Unicode)")));
		if(msg.getDate() != null) sb.replaceAll("%date%", URLEncoder.encode(msg.getDate().toString(), getProperty("encoding", "ISO-8859-1")));
		sb.replaceAll("%text%", URLEncoder.encode(msg.getText(), getProperty("encoding", "ISO-8859-1")));
		if(msg.getRefNo() != null) sb.replaceAll("%refNo%", URLEncoder.encode(msg.getRefNo(), getProperty("encoding", "ISO-8859-1")));
		sb.replaceAll("%recipient%", msg.getRecipient());
		sb.replaceAll("%from%", msg.getFrom());
		sb.replaceAll("%failureCause%", URLEncoder.encode(msg.getFailureCause().toString(), getProperty("encoding", "ISO-8859-1")));
		sb.replaceAll("%messageStatus%", msg.getMessageStatus().toString());
		return sb.toString();
	}
	
}
